﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Truron.Purchase.Api.Utility;
using Truron.Purchase.Model;
using Truron.Purchase.Model.RemoteModel;
using Truron.Purchase.Utility;
using Truron.Purchase.Utility.RedisHelper;

namespace Truron.Purchase.Api.Filter
{
    public class AuthFilterFilterAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext context)
        {

            bool isSkip = false;
            //controller验证
            if(context.Controller.GetType().GetCustomAttributes(typeof(SkipActionFilterAttribute), true).Any())
                isSkip = true;
            //Action验证
            if (!isSkip && context.ActionDescriptor is ControllerActionDescriptor controllerActionDescriptor)
            {
                if (controllerActionDescriptor.MethodInfo.GetCustomAttributes(inherit: true)
                   .Any(a => a.GetType().Equals(typeof(SkipActionFilterAttribute))))
                    isSkip = true;
            }
            if(!isSkip)
            {
                string token = context.HttpContext.Request.Headers["Authorization"].ToString();
                if (String.IsNullOrEmpty(token))
                    context.Result = new JsonResult(new ResultData(ErrorCodeConst.TokenError));
                var userCache = RedisBase.Item_Get<UserCache>(token);
                if (userCache == null)
                    context.Result = new JsonResult(new ResultData(ErrorCodeConst.TokenError));
            }
            base.OnActionExecuting(context);
        }
    }
}
